package com.dc.datacollect.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dc.datacollect.components.timer.TimerManager;
import com.dc.datacollect.entity.Collect;
import com.dc.datacollect.service.CollectInstanceService;
import com.dc.datacollect.service.CollectService;
import com.dc.datacollect.helpers.BeanProvide;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CollectScheduled {

    @Autowired
    private CollectInstanceService collectInstanceService;

    @Autowired
    private TimerManager timerManager;

    @Autowired
    private BeanProvide beanProvide;

    @Autowired
    private CollectService collectService;

//    @Scheduled(cron = "00 */1 * ? * *")
    @PostConstruct
    public void collectEndTimeExecutor() {
        LambdaQueryWrapper<Collect> collectQueryWrapper = new LambdaQueryWrapper<>();
        collectQueryWrapper.gt(Collect::getEndTime,new Date());
        List<Collect> collectList = collectService.list(collectQueryWrapper);
        saveTimer(collectList);
    }
    public void saveTimer(List<Collect> collectList) {
        log.info("更新定时任务，数量：{}",collectList.size());
        collectList.forEach(collect -> {
            timerManager.addTimer(String.valueOf(collect.getId()),()->{
                collectInstanceService.exportCollectForNoticeHandle(collect.getId());
            },collect.getEndTime().getTime());
        });
    }
    public void removeTimer(Long collectId) {
        timerManager.removeTimer(String.valueOf(collectId));
    }

}
